package com.gateio.flutter.lib_core

import android.util.Log
import androidx.annotation.Keep

/**
 * Author: Shper
 * Created: 2023/7/7
 * Flutter 消息中心，用于接收原生端消息
 */
typealias GTMessageCenterCallback = (actionType: String, actionName: String, messageJson: String) -> Unit

@Keep
object GTFlutterMessageCenter {

    private val _listenerMap: MutableMap<String, MutableList<GTMessageCenterCallback?>> = mutableMapOf()

    // 增加监听具体分类的通知
    @JvmStatic
    fun <E : Enum<E>> addListener(action: Enum<E>, callback: GTMessageCenterCallback) {
        val actionKey = _generateActionKeyByEnum(action)
        val callbackList = _listenerMap[actionKey] ?: mutableListOf()
        callbackList.add(callback)
        _listenerMap[actionKey] = callbackList
    }

    // 增加 监听全部分类的通知
    @JvmStatic
    fun <E : Enum<E>> addListener(actions: List<Enum<E>>, callback: GTMessageCenterCallback) {
        if (actions.isEmpty()) {
            Log.d("GTFlutter", "The action list is empty.")
            return
        }
        actions.forEach { action ->
            addListener(action, callback)
        }
    }

    @JvmStatic
    fun <E : Enum<E>> removeListener(action: Enum<E>, callback: GTMessageCenterCallback) {
        val actionKey = _generateActionKeyByEnum(action)
        val callbackList = _listenerMap[actionKey]
        callbackList?.let { list ->
            // 清理一遍空数据
            list.removeAll { it == null }
            list.remove(callback)
        }
    }

    @JvmStatic
    fun <E : Enum<E>> removeListener(actions: List<Enum<E>>, callback: GTMessageCenterCallback) {
        if (actions.isEmpty()) {
            Log.d("GTFlutter", "The action list is empty.")
            return
        }
        actions.forEach { action ->
            removeListener(action, callback)
        }
    }

    // 发送消息
    @JvmStatic
    fun <E : Enum<E>> sendMessage(action: Enum<E>, messageJson: String = "{}") {
        _sendMessage(action.javaClass.simpleName, action.name, messageJson)
    }

    // 发送消息
    @JvmStatic
    fun <E : Enum<E>> sendMessage(action: Enum<E>, messageMap: Map<String, Any?> = mutableMapOf()) {
        _sendMessage(action.javaClass.simpleName, action.name, GTLibCoreFlutterPlugin.gson.toJson(messageMap))
    }

    // 发送消息到 Flutter 侧
    internal fun _sendMessage(actionType: String, actionName: String, messageJson: String) {
        GTLibCoreFlutterPlugin.messageChannelList.forEach { messageChannelFlutterApi ->
            try {
                messageChannelFlutterApi.handleMessage(actionType, actionName, messageJson){}
            } catch (e: Exception) {
                // ignore
            }
        }
    }

    // 消息分发
    internal fun _dispatchMassage(actionType: String, actionName: String, messageJson: String) {
        val actionKey = _generateActionKey(actionType, actionName)
        val callbackList = _listenerMap[actionKey]
        callbackList?.let { list ->
            list.forEach { callback ->
                try {
                    callback?.invoke(actionType, actionName, messageJson)
                } catch (e: Exception) {
                    // ignore
                }
            }
            // 清理一遍空数据
            list.removeAll { it == null }
        }
    }

    // 根据 枚举生成 actionKey
    internal fun <E : Enum<E>> _generateActionKeyByEnum(action: Enum<E>): String {
        return "${action.javaClass.simpleName}.${action.name}"
    }

    // 根据 actionType 和 actionName 生成 actionKey
    internal fun _generateActionKey(actionType: String, actionName: String): String {
        return "$actionType.$actionName"
    }

}